﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace Group_Mail
{
    public partial class frmConsole : Form
    {
        #region Delegates

        public delegate void WriteConsoleHandler(string message);

        #endregion

        public frmConsole()
        {
            InitializeComponent();
        }

        protected override CreateParams CreateParams
        {
            get
            {
                var mdiCp = base.CreateParams;
                mdiCp.ClassStyle = mdiCp.ClassStyle | 0x200;
                return mdiCp;
            }
        }

        private void frmConsole_Load(object sender, EventArgs e)
        {
            txtConsole.BackColor = ColorTranslator.FromHtml("#404040");
            txtConsole.ForeColor = Color.White;
            Manager.ThreadComplete += Manager_ThreadComplete;
            Job.SendComplete += Job_SendComplete;
            Job.SendFail += Job_SendFail;
        }

        private void Job_SendFail(string message)
        {
            WriteConsole(message);
        }

        private void Job_SendComplete(string to)
        {
            WriteConsole(string.Format("Send complete to {0}", to));
        }

        private void Manager_ThreadComplete(string id, MessageStatus status)
        {
            var message = Manager.GetMessageById(id);
            var account = Manager.GetAccountName(message.AccountId);
            var group = Manager.GetGroupName(message.GroupId);
            switch (status)
            {
                case MessageStatus.Complete:
                    WriteConsole(string.Format("Complete send from {0} to {1}.", account, group));
                    break;
                case MessageStatus.Fail:
                    WriteConsole(string.Format("Fail send from {0} to {1}.", account, group));
                    break;
            }
        }

        public void WriteConsole(string message)
        {
            var parameters = new object[] {message};
            Invoke(new WriteConsoleHandler(msg => txtConsole.Text += Environment.NewLine + msg), parameters);
        }

        private void txtConsole_TextChanged(object sender, EventArgs e)
        {
            txtConsole.SelectionStart = txtConsole.Text.Length;
            txtConsole.ScrollToCaret();
        }
    }
}